<?php

namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Validate;

use app\index\model\Member;
use app\index\model\SendOrder;
use app\index\model\Qrcode;
use app\index\model\Express;
use app\index\model\Order;

class Sender extends Controller
{
    protected $middleware = [
        'CheckTruth' 	=> ['only' 	=> ['index', 'getOrder', 'getSendOrder'] ],
    ];

    public function index(){
        return view('order-receiving');
    }

    // 注册成为快递员
    public function register(){
        return view('delivery-staff');
    }

    // 等待验证
    public function wait(){
        return view('msg');
    }

    // 保存身份信息
    public function saveInfo(){
        // 获取相关信息
        $info = request()->only(['uname', 'captcha', 'id_card', 'image'], 'post');
        if(count($info) != 4) return json(mesg(-1, '必填项不能为空'));

        if($info['captcha'] != session('captcha')){
            session('captcha', null);
            $result = [
                'msg' => '手机验证码不正确',
                'code' => -1,
            ];
            return $result;
        }
        
        $image = [];
        foreach(json_decode($info['image']) as $item){
            $image[] = $item;
        }
        $user = new Member();
        $res = $user->save([
            'memb_IDCard'   => $info['id_card'],
            'memb_truename' => $info['uname'],
            'memb_is_truth' => 2,
            'memb_cardImage'=> json_encode($image),
        ], ['memb_id' => session('user.id')]);
        if($res)
            return json(['code'=>0, 'msg'=>'success']);
        else
            return json(mesg(-1, 'error'));
    }

    public function uploadIdCard(){
        $image = \think\Image::open(request()->file('image'));
        $name = getMillisecond() . '.jpg';
        $image->thumb(1000, 1000)->save(env('root_path'). 'data/uploads/' . $name, null, 100);
        return json(mesg(0, 'success', ['src'=>$name]));
    }
    
    /**
     * 删除上传的照片
     * 
     */
    public function deleteUpload($url){
        $path = env('root_path'). 'data\uploads\\' . $url;
        if(file_exists($path)){
            // $res = unlink($path);
            return mesg(0, 'ok');
        }else{
            return '文件不存在';
        }
    }
    
    //检测二维码是否发布
    public function checkQrcode(){
        $qrid = input('code', null);
        if(empty($qrid)) return json(mesg(-1, '二维码错误'));
        $sorder = new SendOrder();
        $code = [];
        foreach ($qrid as $v) {
            if($sorder->checkQrcode($v)) $code[] = $v;
        }
        if(!empty($code)) return json(mesg(-1, '当前所选中存在已发布的二维码', $code));
        return json(mesg(0, 'ok'));
    }

    //发布订单
    public function saveSendOrder(){
        if(request()->isPost()){
            $qrid = input('code', null);
            if(empty($qrid)) return json(mesg(-1, '二维码错误'));
            $isEx = SendOrder::where('send_uid',session('user.id'))
            ->where('send_status', '<>', 3)->where('send_qrcode_id', $qrid)->find();
            // $code = [];
            // foreach ($qrid as $v) {
            //     $qr = $isEx->where('send_qrcode_billcode', 'like', '%'. $v .'%')->value('id');
            //     if(!empty($qr)) $code[] = $v;
            // }
            if(!empty($isEx)) return json(mesg(-1, '当前二维码已发布'));
            try {
                $addr = request()->post('receiver_info');
                $sOrder = new SendOrder;
                $sOrder->send_code   = randOrder('F');
                $sOrder->send_uid    = session('user.id');
                $sOrder->send_addr   = $addr;
                $sOrder->send_qrcode_id = $qrid;
                $sOrder->save();
                // saveOrderCache($sOrder->send_code);
                return json(['code'=>0, 'msg'=>'发布成功']);
            } catch (\Throwable $th) {
                throw $th;
                return json(['code'=>-5, 'msg'=>'fail']);
            }
        }
    }

    // 获取寄件订单
    public function getSo(){
        $page = input('page', 0);
        $status = input('status', 2);
        $where = [];
        if($status != 0) {
            $where[] = ['orde_sender_id', '=', session('user.id')];
        }
        $orders = Order::field('orde_o_code as code, orde_sender_info as sender, orde_receiver_info as receiver, orde_pickupTime as time, create_time')
        ->where($where)
        ->where('orde_status', $status)
        ->limit($page * config('app.page_num'), config('app.page_num'))
        ->select();
        // $sends = db('order')->field('orde_o_code as code, orde_sender_info as addr ,create_time, sort')
        // ->where()
        return json(['code'=>0, 'msg'=>'success', 'data'=>$orders]);
    }
    
    // 接寄件单
    public function saveSo(){
        $num = request()->post('code');
        $order = new Order();
        try {
            $order->save([
                'orde_status'   => 2,
                'orde_sender_id'     => session('user.id'),
            ], ['orde_o_code' => $num]);
            // pullTask($num);
            return json(mesg(0, 'success'));
        } catch (\Throwable $th) {
            return json(mesg(-5, 'fail'));
        }
    }
    
    //获取送件订单列表
    public function getOrder(){
        $page = input('page', 0);
        $status = input('status', 1);
        $where = [];
        if($status != 0) {
            $where[] = ['sender_id', '=', session('user.id')];
        }
        $orders = db('send_order')->field('send_code as code, send_addr as addr, create_time')
        ->where($where)
        ->where('send_status', $status)
        ->limit($page * config('app.page_num'), config('app.page_num'))
        ->select();
        // $sends = db('order')->field('orde_o_code as code, orde_sender_info as addr ,create_time, sort')
        // ->where()
        return json(['code'=>0, 'msg'=>'success', 'data'=>$orders]);
    }

    //接单
    public function getSendOrder(){
        $num = request()->post('order_code');
        $order = new SendOrder();
        try {
            $order->save([
                'send_status'   => 1,
                'sender_id'     => session('user.id'),
                'get_time'      => date('Y-m-d H:i:s'),
            ], ['send_code' => $num]);
            // pullTask($num);
            return json(mesg(0, 'success'));
        } catch (\Throwable $th) {
            return json(mesg(-5, 'fail'));
        }
    }

    // 查看二维码
    public function showCode(){
        $code = input('code');
        $qrcode = SendOrder::where('send_code', $code)->where('sender_id', session('user.id'))->where('send_status', 1)->find();
        if(empty($qrcode)){
            return json(mesg('-1', 'fail'));
        }
        $qrcode = Qrcode::where('id', $qrcode->send_qrcode_id)->find();
        $kdcodes = json_decode($qrcode->kdcode);
        $shelves = [];
        foreach($kdcodes as $v) {
            $content = Express::where('billcode', $v)->value('content');
            $shelves[] = substr($content, 0, 8);
        }
        return view('', ['code' => $shelves]);
    }
    public function getQrcode($code){
        $qrcode = SendOrder::where('send_code', $code)->where('sender_id', session('user.id'))->where('send_status', 1)->find();
        if(empty($qrcode)){
            return json(mesg('-1', 'fail'));
        }
        $path = Qrcode::where('id', $qrcode->send_qrcode_id)->value('qrcode');
        $base64 = baseImage($path);
        return json(mesg(0, 'success', $base64));
    }

    // 收到货物
    public function receiveGood(){
        $num = request()->post('code');
        $order = SendOrder::where('code', $num)->find();
        if(!empty($order)){
            if($order->uid == session('user.id')){
                // Member::updateBalance($order->send_id);
                insertPointLog('收件', 1);
            }elseif($order->sender_id == session('user.id')){
                $order->status = 2;
            }else{
                return ;
            }
            return json(['code'=>0, 'msg'=>'操作完成']);
        }
    }

    // 取消订单
    public function closeSendOrder(){
        $num = request()->post('code');
        if(empty($num)){
            return json(mesg(-1, '失败'));
        }
        try {
            $order = new SendOrder();
            $order->where('send_code', $num)->where('send_uid', session('user.id'))->update(['send_status' => 3]);
            return json(['code'=>0, 'msg'=>'取消成功']);
        } catch (\Throwable $th) {
            throw $th;
            // return json(['code'=>-5, 'msg'=>$th->getMessage()]);
        }
    }
    // 上门取件
    public function pickorder(){
        return view('order-picking');
    }
}
